<template>
  <el-dialog :model-value="showQuestionTypeVisible" :title="isCourseCategory ? '视频课程' : '题库列表'" width="50%"
    :before-close="resetForm" :close-on-click-modal="false">
    <el-form :model="form" label-width="auto" @keydown.enter.prevent="getData">
      <el-row :gutter="12">
        <el-col :span="8">
          <el-form-item :label="isCourseCategory ? '课程名称' : '题目名称'">
            <el-input v-model="form.questionName" :placeholder="isCourseCategory ? '请输入课程名称' : '请输入题目名称'"
              @blur="nameBlur"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="isCourseCategory ? '课程类型' : '题目类型'">
            <el-select v-model="form.questionType" clearable placeholder="请选择" style="width: 100%" @change="nameBlur">
              <el-option v-for="item in typeOptions_two" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="同级分组是否存在">
            <el-select v-model="form.inGroup" clearable placeholder="请选择" style="width: 100%" @change="nameBlur">
              <el-option label="已存在" value="01"></el-option>
              <el-option label="不存在" value="02"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="!isCourseCategory">
          <div style="display: flex">
            <el-upload class="upload-component" :action="excelServer" :headers="headers" :show-file-list="false"
              :on-success="handleImportSuccess" :on-error="handleImportError" :before-upload="beforeImportUpload"
              :disabled="uploadLoading">
              <el-button type="primary" :loading="uploadLoading">
                <el-icon>
                  <Upload />
                </el-icon>
                导入题库
              </el-button>
            </el-upload>
            <el-button v-ripple @click="handleDownloadTemplate" :loading="downloadLoading" style="margin-left: 20px">
              <el-icon>
                <Download />
              </el-icon>
              下载题库模板
            </el-button>
          </div>
        </el-col>
      </el-row>
    </el-form>

    <el-table ref="tableRef" v-loading="tableLoading" :data="tableData" row-key="id"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" reserve-selection width="55" />
      <el-table-column label="ID" prop="id" />
      <el-table-column :label="isCourseCategory ? '课程标题' : '题目标题'" width="400">
        <template #default="scope">
          <div>{{ scope.row.questionName }}</div>
        </template>
      </el-table-column>
      <el-table-column label="车型" prop="carModelList" v-if="isCourseCategory">
        <template #default="scope">
          {{
            scope.row.carModelList
              ? scope.row.carModelList.map((e: any) => e.carName).join(',')
              : ''
          }}
        </template>
      </el-table-column>
      <el-table-column label="课程类型" prop="questionType" v-if="isCourseCategory" width="150">
        <template #default="scope">
          <el-button v-if="scope.row.questionType == '3'" round size="small" plain>
            实拍讲解
          </el-button>
          <el-button v-if="scope.row.questionType == '4'" round size="small" type="primary">
            考点视频
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="科目" prop="categoryId" v-if="isCourseCategory" width="150">
        <template #default="scope">
          <el-button v-if="scope.row.categoryId == '1'" round size="small" type="warning">
            科目一
          </el-button>
          <el-button v-if="scope.row.categoryId == '2'" round size="small" type="warning">
            科目二
          </el-button>
          <el-button v-if="scope.row.categoryId == '3'" round size="small" type="warning">
            科目三
          </el-button>
          <el-button v-if="scope.row.categoryId == '4'" round size="small" type="warning">
            科目四
          </el-button>
        </template>
      </el-table-column>
      <el-table-column :label="isCourseCategory ? '封面图' : '图片'">
        <template #default="scope">
          <img v-if="scope.row.questionImg" style="width: 30px; height: 30px; cursor: pointer"
            :src="scope.row.questionImg" @click="openPreviewImg(scope.row.questionImg)" />
        </template>
      </el-table-column>
      <!-- 视频链接 -->
      <el-table-column label="题目类型" v-if="isQuestionCategory">
        <template #default="scope">
          <el-button v-if="scope.row.questionType == '1'" round size="small" plain>单选题
          </el-button>
          <el-button v-if="scope.row.questionType == '0'" round size="small" type="warning" plain>多选题
          </el-button>
          <el-button v-if="scope.row.questionType == '2'" round size="small" type="danger" plain>判断题
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button link type="primary" @click="checkDetail(scope.row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="table-pagination">
      <el-pagination size="default" :current-page="pageNum" :page-size="pageSize" :page-sizes="[10, 50, 100, 200]"
        layout="sizes, prev, pager, next" :total="pageTotal" :background="true" @size-change="objectOneSizeChange"
        @current-change="objectOneCurrentChange" />
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" :loading="editLoading" @click="handleSubmit">确认</el-button>
        <el-button @click="resetForm">取消</el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog v-model="previewImg" :close-on-click-modal="false">
    <div style="text-align: center">
      <img :src="openImg" alt="" />
    </div>
  </el-dialog>
  <el-dialog v-model="checkInfo" title="查看题目详情" width="35%" :close-on-click-modal="false">
    <div style="height: 800px; overflow: auto">
      <el-form :model="checkForm" label-width="80" style="width: 700px">
        <el-form-item label="ID" prop="sort">
          <el-input v-model="checkForm.id" :rows="3" :disabled="true" />
        </el-form-item>
        <el-form-item label="车型" prop="card_type">
          <el-checkbox-group v-model="cardvaluelist" @change="handleCheckedCitiesChange" :disabled="true">
            <el-checkbox v-for="city in cardlist" :label="city.value" :key="city.value">
              {{ city.label }}({{ city.tag }})
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="题目名称" prop="name">
          <el-input type="textarea" :rows="4" v-model="checkForm.questionName" :disabled="true" />
        </el-form-item>
        <el-form-item label="题目类型" prop="cont_type">
          <!-- 单选 -->
          <el-radio v-model="radio" label="2" :disabled="true">判断题</el-radio>
          <el-radio v-model="radio" label="1" :disabled="true">单选题</el-radio>
          <el-radio v-model="radio" label="0" :disabled="true">多选题</el-radio>
        </el-form-item>
        <!-- 单选题 -->
        <div class="contlist_list" v-if="radio != '2'">
          <el-form-item label="题目A："><el-input class="contliststyle" v-model="checkForm.questionA"
              :disabled="true" /></el-form-item>
          <el-form-item label="题目B："><el-input class="contliststyle" v-model="checkForm.questionB"
              :disabled="true" /></el-form-item>
          <el-form-item label="题目C："><el-input class="contliststyle" v-model="checkForm.questionC"
              :disabled="true" /></el-form-item>
          <el-form-item label="题目D："><el-input class="contliststyle" v-model="checkForm.questionD"
              :disabled="true" /></el-form-item>
        </div>
        <!-- 单选题 -->
        <!-- 判断题 -->
        <div class="contlist_list" v-if="radio == '2'" :disabled="true">
          <el-form-item label="题目A："><el-input class="contliststyle" v-model="checkForm.questionA" /></el-form-item>
          <el-form-item label="题目B："><el-input class="contliststyle" v-model="checkForm.questionB" /></el-form-item>
        </div>
        <el-form-item label="答案" prop="answer">
          <el-input v-model="checkForm.answer" :disabled="true" />
        </el-form-item>
        <el-form-item label="图片" prop="name">
          <el-upload class="avatar-uploader" :disabled="true" style="
              border: 1px dashed var(--el-border-color-darker);
              border-radius: 6px;
              overflow: hidden;
            " :action="server" :headers="headers" :show-file-list="false" :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <el-image v-if="storeLogo" :src="storeLogo" class="avatar" fit="contain"></el-image>
            <i v-else class="el-icon-plus avatar-uploader-icon"><el-icon>
                <Plus />
              </el-icon></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="题目解析" prop="analysis">
          <el-input type="textarea" :rows="6" v-model="checkForm.questionAnalysis" :disabled="true" />
        </el-form-item>
        <el-form-item label="速学速记" prop="fastStudy">
          <el-input type="textarea" :rows="6" v-model="checkForm.fastStudy" :disabled="true" />
        </el-form-item>
        <el-form-item label="视频讲解" prop="video" :disabled="true">
          <el-input :disabled="true">
            <template #append>
              <el-upload class="video-uploader" :action="server" :headers="headers" :show-file-list="false"
                :on-success="handleSuccess" :before-upload="beforeUpload" accept="video/*">
                <el-button style="color: #2b8dfa" type="primary" :disabled="true">点击上传</el-button>
              </el-upload>
            </template>
          </el-input>
          <!-- 上传视频部分 -->
          <div style="clear: both"></div>
          <video v-if="videoUrl_add" :src="videoUrl_add" controls class="video-preview"></video>
        </el-form-item>
      </el-form>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import {
  getCanSelectQuestion,
  relationQuestion,
  getcarmodellist,
  exportQuestion,
  putquestioncategory
} from '@/api/questionbank'
import { ElMessage, UploadProps } from 'element-plus'
import { useUserStore } from '@/store/modules/user'

const props = defineProps({
  showQuestionTypeVisible: {
    type: Boolean
  },
  editInfo: {
    type: Object,
    default: () => {
      return { id: '' }
    }
  }
})

const typeOptions_two = [
  {
    value: '3',
    label: '实拍讲解'
  },
  {
    value: '4',
    label: '考点视频'
  }
]

console.log(props.editInfo, 'props.editInfo===')

const isCourseCategory = computed(() => ['2', '3'].includes(props.editInfo.categoryIds))
const isQuestionCategory = computed(() => ['1', '4'].includes(props.editInfo.categoryIds))

const userStore = useUserStore()

// token
let { accessToken } = userStore
const headers = { Authorization: 'Bearer ' + accessToken, store_id: localStorage.getItem('lty-store-id') }
// 图片上传地址
let server = `${import.meta.env.VITE_API_URL}/api/common/upload/wangeditor`
const excelServer = `${import.meta.env.VITE_API_URL}ds-question-group/importXlsx/${props.editInfo.id}`

const storeLogo = ref('')
const videoUrl_add = ref('')

const checkInfo = ref(false)

const checkForm = reactive({
  id: '',
  questionName: '',
  answer: '',
  questionAnalysis: '',
  fastStudy: '',
  questionA: '',
  questionB: '',
  questionC: '',
  questionD: ''
})
const radio = ref('2')
const cardvaluelist = ref()
const cardvalueliststring = ref()
const handleCheckedCitiesChange = (val: any) => {
  console.log(val) //请求用户列表接口
  cardvalueliststring.value = val.toString()
}

const checkDetail = (e: any) => {
  console.log(e, 'e===')
  checkInfo.value = true
  Object.assign(checkForm, e)
  cardvaluelist.value = e.carIds.split(',')
  radio.value = e.questionType.toString()
  storeLogo.value = e.questionImg
  videoUrl_add.value = e.videoUrl
}

//展示不同的题目类型
const typeOptions = [
  {
    value: '2',
    label: '判断题'
  },
  {
    value: '1',
    label: '单选题'
  },
  {
    value: '0',
    label: '多选题'
  }
]

const form = reactive({
  carId: '',
  questionType: '',
  questionName: '',
  inGroup: ''
})

const tableData = ref([])
const pageNum = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)
const selectIds = ref<string[]>([])
const tableRef = ref()
const tableLoading = ref(false)
const editLoading = ref(false)

const emit = defineEmits(['closeDialog'])

const resetForm = () => {
  emit('closeDialog')
}

async function handleSubmit() {
  try {
    editLoading.value = true
    const res = await relationQuestion({
      questionIds: [...new Set(selectIds.value)],
      groupIds: props.editInfo.id
    })
    if (res) {
      emit('closeDialog', true)
      ElMessage.success('添加成功')
    }
  } catch (e) {
  } finally {
    editLoading.value = false
  }
}

function handleSelectionChange(data: any[]) {
  selectIds.value = data.map((item) => item.id)
}

const objectOneCurrentChange = (val: number) => {
  pageNum.value = val
  getData()
}
const objectOneSizeChange = (val: number) => {
  pageSize.value = val
  pageNum.value = 1
  getData()
}

async function getData() {
  console.log(props.editInfo.pageUrlType, "props.editInfo.pageUrlType==");
  let type = null
  if (props.editInfo.pageUrlType === '04') {
    type = 0
  } else {
    type = props.editInfo.categoryIds === '2' || props.editInfo.categoryIds === '3'
      ? 1
      : JSON.parse(props.editInfo.remark).type
  }

  const obj: Record<string, any> = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    categoryId: props.editInfo.categoryIds,
    carIds: props.editInfo.carIds,
    isGroup: '02',
    groupId: props.editInfo.id,
    type,
    pageUrlType: props.editInfo.pageUrlType
  }

  for (const key in form) {
    const typedKey = key as keyof typeof form
    if (form[typedKey] !== '') {
      obj[typedKey] = form[typedKey]
    }
  }
  // return
  try {
    tableLoading.value = true
    const res = await getCanSelectQuestion(obj)
    if (res.code === '00000') {
      tableData.value = res.data.list
      pageTotal.value = res.data.total
    }
  } catch (e) {
  } finally {
    tableLoading.value = false
  }
}

const previewImg = ref(false)
const openImg = ref('')
const openPreviewImg = (e: string) => {
  previewImg.value = true
  openImg.value = e
}

const cardlist = ref([{ value: '', label: '', tag: '' }])
const getcarmodellistinfo = async () => {
  let obj = {}
  const res = await getcarmodellist.getcarmodelId(obj)
  if (res.code === '00000') {
    cardlist.value = res.data
  }
}

const handleAvatarSuccess = (file: any) => {
  console.log(file)
  storeLogo.value = file.data.url
}
//上传限制大小格式等
const beforeAvatarUpload = (file: any) => {
  const isLt2M = file.size / 10240 / 10240 < 2
  if (file.type != 'image/jpeg' && file.type != 'image/png' && file.type != 'image/gif') {
    ElMessage.error('图片类型仅支持JPG/PNG/GIF格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 20MB!!')
    return false
  }
}
const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  const isVideo = file.type.includes('video/')
  const isLt500M = file.size / 1024 / 1024 < 500

  if (!isVideo) {
    ElMessage.error('只能上传视频文件!')
    return false
  }
  if (!isLt500M) {
    ElMessage.error('视频大小不能超过500MB!')
    return false
  }
  return true
}

const EXCEL_MIME_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
const MAX_FILE_SIZE = 50 * 1024 * 1024
const uploadLoading = ref(false)

const beforeImportUpload = (file: File): boolean => {
  const isExcel = file.type === EXCEL_MIME_TYPE
  const isLt50 = file.size < MAX_FILE_SIZE

  if (!isExcel) {
    ElMessage.error('只能上传Excel文件!')
    return false
  }

  if (!isLt50) {
    ElMessage.error('文件大小不能超过50MB!')
    return false
  }

  uploadLoading.value = true
  return true
}

interface ImportResponse {
  code: string
  msg: string
  data?: any
}

const handleImportSuccess = (response: ImportResponse) => {
  uploadLoading.value = false

  if (response.code === '0') {
    ElMessage.success('导入成功')
    getData() // 刷新数据
  } else {
    ElMessage.error(response.msg || '导入失败')
  }
}

const handleImportError = (error: any) => {
  uploadLoading.value = false
  console.error('导入失败:', error)
  ElMessage.error('导入失败，请稍后重试')
}

const handleSuccess: UploadProps['onSuccess'] = (response) => {
  console.log(response)
  videoUrl_add.value = response.data.url
  ElMessage.success('视频上传成功!')
}
const nameBlur = (e: any) => {
  pageNum.value = 1
  pageSize.value = 10
  getData()
}

const downloadLoading = ref(false)
const handleDownloadTemplate = async () => {
  try {
    downloadLoading.value = true

    const res = await exportQuestion()

    if (res instanceof Blob) {
      // 创建下载链接
      const link = document.createElement('a')
      link.href = URL.createObjectURL(res)
      link.download = '题库导入模板.xlsx'
      link.style.display = 'none'
      document.body.appendChild(link)
      link.click()

      // 清理
      URL.revokeObjectURL(link.href)
      document.body.removeChild(link)

      ElMessage.success('模板下载成功')
    } else {
      ElMessage.error('下载失败')
    }
  } catch (error) {
    console.error('下载模板失败:', error)
    ElMessage.error('下载失败，请稍后重试')
  } finally {
    downloadLoading.value = false
  }
}

onMounted(() => {
  getData()
  getcarmodellistinfo()
})
</script>

<style scoped lang="scss">
.table-pagination {
  display: flex;
  margin-top: 16px;
  justify-content: center;

  // 分页对齐方式
  &.left {
    justify-content: flex-start;
  }

  &.center {
    justify-content: center;
  }

  &.right {
    justify-content: flex-end;
  }
}
</style>
